package com.example.qsmx;

import com.example.qsmx.Util.MyDBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.sql.*;

@WebServlet("/revise-value")
public class ReviseQSMX extends HttpServlet {
    public static void rmFileImg(int id, String realPath) throws SQLException {
        // 将要获取的封面文件地址
        String coverFile = null;

        // 连接数据库
        Connection connection = MyDBUtil.getConnection();

        // SQL 获取语句
        String deleteSql = "SELECT `value-cover` FROM qsmxvalue WHERE `value-id` = ?";

        // 放入删除的封面对应的 id
        PreparedStatement preparedStatement = connection.prepareStatement(deleteSql);
        preparedStatement.setInt(1, id);

        // 获取结果集
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.equals(null)){
            return;
        }
        while (resultSet.next()){
            coverFile = resultSet.getString("value-cover");
        }


        // 删除对应的文件
        if (coverFile != null) {
            File file = new File(coverFile); // 替换为要删除文件的实际路径

        if (file.exists()) {
            if (file.delete()) {
                System.out.println("文件删除成功");
            } else {
                System.out.println("文件删除失败");
            }
        } else {
            System.out.println("文件不存在，无需删除。");
        }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取要删除的语句
        String id = req.getParameter("userid-1");
        int i = Integer.parseInt(id);

        // 删除对应的封面
        String realPath = getServletContext().getRealPath("/");
        try {
            rmFileImg(i, realPath);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 连接数据库
        Connection connection = MyDBUtil.getConnection();


        // SQL 删除语句
        String deleteSql = "DELETE FROM qsmxvalue WHERE `value-id` = ?";
        try {
            PreparedStatement pstmt = connection.prepareStatement(deleteSql);

            // 设置 WHERE 子句的条件值
            pstmt.setInt(1, i);

            // 执行删除操作
            pstmt.executeUpdate();

            req.getRequestDispatcher("/WEB-INF/my-interface.jsp").forward(req,resp);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

